﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace RunGun
{
    /// <summary>
    /// Concrete sealed class that contains and applies texture shader
    /// </summary>
    public sealed class TextureEffect : IShaderEffect
    {
        /// <summary>
        /// Sets the effect.
        /// </summary>
        public Effect Effect { private get; set; }

        /// <summary>
        /// Applies the ambient light effect to a model to be drawn.
        /// </summary>
        /// <param name="mesh">The model mesh.</param>
        /// <param name="camera">The camera.</param>
        public void ApplyEffect(ModelMesh mesh, CameraBase camera)
        {
            foreach (var part in mesh.MeshParts)
            {
                part.Effect = Effect;
                Effect.Parameters["DiffuseLightDirection"].SetValue(camera.Position);
                Effect.Parameters["World"].SetValue(camera.World * mesh.ParentBone.Transform);
                Effect.Parameters["View"].SetValue(camera.View);
                Effect.Parameters["Projection"].SetValue(camera.Projection);
                Effect.Parameters["WorldInverseTranspose"].SetValue(Matrix.Transpose(Matrix.Invert(mesh.ParentBone.Transform * camera.World)));
                var viewVec = Vector3.Transform(camera.Target - camera.Position, Matrix.CreateRotationY(0));
                viewVec.Normalize();
                Effect.Parameters["ViewVector"].SetValue(viewVec);
            }
        }
    }
}